//
//  LTXBaseRequest.m
//  LazySchoolmate
//
//  Created by 李宗帅 on 2017/12/5.
//  Copyright © 2017年 李宗帅. All rights reserved.
//

#import "LTXBaseRequest.h"
#import "LTXRequestLogger.h"
#import <YZCategory/NSString+EncryptSha.h>

typedef enum : NSUInteger {
    HDSystemErrorCodeTypeSuccess           = 200,   // 获取数据成功
    HDSystemErrorCodeTypeExpired           = 401,   // 登录token过期
//    WLWSystemErrorCodeTypeAuthUser          = 603,   // 用户未授权,跳转登录
//    WLWSystemErrorCodeTypeNotLogin          = 604,   // 未登录
//    WLWSystemErrorCodeTypeNeedUpdate        = 605,   // 有版本更新
//    WLWSystemErrorCodeTypePromptMsg         = 606,   // 提示服务端信息
//    WLWSystemErrorCodeTypeUpdateAppKey      = 607,   // 请求appkey
//    WLWSystemErrorCodeTypeAccountAbnormal   = 609    // 账号冻结,打印后台返回的信息
} HDSystemErrorCodeType;

@interface LTXBaseRequest ()


//@property (nonatomic, copy) NSString *deviceType;
//
//@property (nonatomic, copy) NSString *deviceId;
//
//@property (nonatomic, copy) NSString *versionCode;
//
@property (nonatomic, copy) NSString *app_id;//app_ID  当前是HD3?

@property (nonatomic, copy) NSString *language;//语言.....

@end

@implementation LTXBaseRequest


- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    
    [self commonSetup];
    
    return self;
}

#pragma mark __PRI__
- (void)commonSetup {
//    _deviceType = @"ios";
//    _deviceId = [FCUUID uuidForDevice];
//    _versionCode = [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
//    _channel = [self getAppChannel];
//    当前的语言
    NSArray *langArr1 = [[NSUserDefaults standardUserDefaults] valueForKey:@"AppleLanguages"];
    NSString *language1 = langArr1.firstObject;
    _app_id = @"hd31806";
    _language = [language1 isEqualToString:@"en"]?@"en":@"zh-cn";
}

- (NSString*)getAppChannel
{
    return  @"appStore";
}


- (YTKRequestMethod)requestMethod
{
    return YTKRequestMethodPOST;
}

- (id)requestNewArgument
{
    return @{
             };
}

- (id)requestArgument
{
    NSMutableDictionary *dict = [self requestNewArgument];
    [dict setValue:_app_id forKey:@"app_id"];
    [dict setValue:_language forKey:@"l"];
    NSInteger now = [[NSDate date] timeIntervalSince1970];
    [dict setObject:[NSString stringWithFormat:@"%ld",now] forKey:@"timestamp"];
    [dict setObject:[self createSignWithDictionary:dict] forKey:@"c_sum"];
    return dict;
}

- (void)startWithCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success failure:(YTKRequestCompletionBlock)failure
{
    [LTXRequestLogger logRequestWithYCLRequest:self YTKRequest:nil error:nil];
    [super startWithCompletionBlockWithSuccess:success failure:failure];
}

#pragma mark --- 创建签名
-(NSString *)createSignWithDictionary:(NSMutableDictionary *)signDict
{
    NSMutableArray *keyArr = [NSMutableArray arrayWithArray:[signDict allKeys]];
    [keyArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult result = [obj1 compare:obj2 options:NSCaseInsensitiveSearch];
        return result==NSOrderedDescending;
    }];
    NSMutableString *str = [NSMutableString string];
    for (NSInteger i=0 ;i<keyArr.count;i++) {
        NSString *key = keyArr[i];
        [str appendFormat:@"%@=%@&", key, signDict[key]];
    }
    NSString *privatekey = @"v1_hd_2018";
    NSString *signStr = [NSString stringWithFormat:@"%@&%@%@", privatekey,str, privatekey];
    
    return [signStr encryptSha256];
}


- (void)setCompletionBlockWithSuccess:(YTKRequestCompletionBlock)success failure:(YTKRequestCompletionBlock)failure
{
    @weakify(self);
    void (^suc)(YTKBaseRequest *) = ^(YTKBaseRequest *request) {
        @strongify(self);
        [LTXRequestLogger logResponseWithYCLRequest:self YTKRequest:request error:nil];
        NSDictionary *metaDic = request.responseJSONObject;
        NSString *code = metaDic[@"code"];
        
        if (code.integerValue == HDSystemErrorCodeTypeExpired)
        {
//            //token过期,跳转到登录的页面,重新登录
//            [[NSNotificationCenter defaultCenter] postNotificationName:kHDNoticeIdentiferUpdateToken object:nil];
        }
        else
        {
            success(request);
        }

    };

    void (^fail)(YTKBaseRequest *) = ^(YTKBaseRequest *request) {
        @strongify(self);
        [LTXRequestLogger logResponseWithYCLRequest:self YTKRequest:request error:request.error];
        failure(request);
    };

    [super setCompletionBlockWithSuccess:suc failure:fail];
}

@end
